package com.imooc.bilibili.rabbit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.imooc.bilibili.domain.UserFollowing;
import com.imooc.bilibili.domain.UserMoment;
import com.imooc.bilibili.domain.dto.DanMuDto;
import com.imooc.bilibili.domain.exception.ConditionException;
import com.imooc.bilibili.service.UserFollowingService;
import com.imooc.bilibili.websocket.WebSocketService;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * ProjectName imooc-bilibili
 *
 * @author xieyucan
 * <br>CreateDate 2022/10/24 11:06
 */
@Slf4j
@Service
public class RabbitReceiveMessage {

    @Resource
    private UserFollowingService userFollowingService;

    @Resource
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = "my.queue")
    public void receiveMessage(@Payload Message message)
    {
        UserMoment userMoment = JSON.parseObject(message.getBody(), UserMoment.class);
        if(userMoment==null){
            throw new ConditionException("消息发送失败");
        }
        Long userId = userMoment.getUserId();
        List<UserFollowing> userFans = userFollowingService.getUserFans(userId);
        for(UserFollowing fan:userFans)
        {
            String key="subscribed"+fan.getUserId();
            String subscribedListStr=(String) redisTemplate.opsForValue().get(key);
            List<UserMoment> subscribedList;
            if(StringUtils.isNullOrEmpty(subscribedListStr)){
                subscribedList=new ArrayList<>();
            }else {
                subscribedList=JSONArray.parseArray(subscribedListStr,UserMoment.class);
            }
            subscribedList.add(userMoment);
            redisTemplate.opsForValue().set(key,JSONObject.toJSONString(subscribedList));
        }
    }

    @RabbitListener(queues = "my.danmu")
    public void receiveDanMuMessage(@Payload Message message) throws IOException {
        DanMuDto danMuDto = JSONObject.parseObject(message.getBody(), DanMuDto.class);
        if(danMuDto==null){
            throw new ConditionException("消息发送失败");
        }
        WebSocketService webSocketService = WebSocketService.WEBSOCKET_MAP.get(danMuDto.getSessionId());
        if(webSocketService.getSession().isOpen())
        {
            webSocketService.sendMessage(danMuDto.getMessage());
        }
    }
}
